package com.zlp.stategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.zlp.common.exception.CustomException;
import com.zlp.common.exception.ServiceException;
import com.zlp.config.LhSupplierProperties;
import com.zlp.dto.test.*;
import com.zlp.enums.SupplierTypeEnum;
import com.zlp.stategy.CouponSupplierStategy;
import com.zlp.utils.MD5Utils;
import com.zlp.utils.MethodUtil;
import com.zlp.utils.RestTemplateUtil;
import com.zlp.utils.SupplierConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Classname LhCouponSupplierStategyImpl
 * @Description 力瀚实现类
 * @Date 2022/9/21 13:20
 * @Created by ZouLiPing
 */
@Service
@Slf4j(topic = "LhCouponSupplierStategyImpl")
public class LhCouponSupplierStategyImpl implements CouponSupplierStategy {

    @Resource
    private LhSupplierProperties lhSupplierProperties;
    @Resource
    private RestTemplateUtil restTemplateUtil;

   private static final  String CONNECT = "&";
   private  static final String APP_KEY = "appKey";

   private  static final String TIMESTAMP = "timestamp";


    @Override
    public String getToken(String timestamp) {

        // 对应签名（sign）：对appKey、timestamp、appSecret用&符号连接后进行md5加密，转大写。md5(appId&timestamp&appSecret).toUpperCase
        StringBuilder stringBuffer = new StringBuilder(lhSupplierProperties.getAppId());
        stringBuffer.append(CONNECT);
        stringBuffer.append(timestamp);
        stringBuffer.append(CONNECT);
        stringBuffer.append(lhSupplierProperties.getAppSecret());
        String token = stringBuffer.toString();
        String sign = MD5Utils.md5(token).toUpperCase();
        log.info("getToken.req appId={},timestamp={},appSecret={},token={},sign={}",lhSupplierProperties.getAppId(),System.currentTimeMillis(),lhSupplierProperties.getAppSecret(),token,sign);
        return sign;
    }






    @Override
    public List<SupplierSkuDTO> getSupplierSkuList(Object paramMap) {

        String domain = lhSupplierProperties.getDomain();
        List<SupplierSkuDTO> supplierSkuDTOList = new ArrayList<>();
        try {
            SupplierSkuReq supplierSkuReq = (SupplierSkuReq) paramMap;
            LhSupplierSkuReq lhSupplierSkuReq = new LhSupplierSkuReq();
            lhSupplierSkuReq.setCusSkuNoList(supplierSkuReq.getCusSkuNoList());
            Map<String, String> headers = new HashMap<>();
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String token = this.getToken(timestamp);
            headers.put(APP_KEY,lhSupplierProperties.getAppId());
            headers.put(TIMESTAMP,timestamp);
            headers.put(SupplierConstant.LH_TOKEN_HEADER,token);
            log.info("getSupplierSkuList.req url={},paramMap={},headers={}",domain+SupplierConstant.LH_CARD_SKU_LIST, JSON.toJSONString(supplierSkuReq),JSON.toJSONString(headers));
            ResponseEntity<JSONObject> result = restTemplateUtil.post(domain+SupplierConstant.LH_CARD_SKU_LIST, headers,lhSupplierSkuReq, JSONObject.class);
            log.info("getSupplierSkuList.resp url={},result={}",domain+SupplierConstant.GET_TOKEN, JSON.toJSONString(result));
            JSONObject jsonObject = result.getBody();
            restTemplateUtil.checkCodeException(jsonObject, SupplierTypeEnum.LI_HAN.getCode());
            String response = jsonObject.getStr("data");
            restTemplateUtil.checkDataException(response);
            List<LhSupplierSkuResp> lhSupplierSkuResps = JSON.parseArray(response, LhSupplierSkuResp.class);
            if (CollectionUtil.isEmpty(lhSupplierSkuResps)){
                return supplierSkuDTOList;
            }
            supplierSkuDTOList = lhSupplierSkuResps.stream().
                    map(lhSupplierSkuResp -> SupplierSkuDTO.convertSupplierSku(lhSupplierSkuResp)).
                    collect(Collectors.toList());
            return supplierSkuDTOList;
        }catch(Exception e){
            log.error("getSupplierSkuList resp error={}",e.getMessage());
            throw new CustomException(500L,e.getMessage(),MethodUtil.getLineInfo());
        }
    }


    @Override
    public SupplierCardCipherDTO createCoupon(Object paramMap) {

        String domain = lhSupplierProperties.getDomain();
        SupplierCardCipherDTO supplierCardCipherDTO = new SupplierCardCipherDTO();
        try {
            LhSupplierCreateReq lhSupplierCreateReq = LhSupplierCreateReq.conventObj(paramMap);
            ArrayList<LhSupplierCreateReq> param = new ArrayList<>();
            param.add(lhSupplierCreateReq);
            Map<String, String> headers = new HashMap<>();
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String token = this.getToken(timestamp);
            headers.put(APP_KEY,lhSupplierProperties.getAppId());
            headers.put(TIMESTAMP,timestamp);
            headers.put(SupplierConstant.LH_TOKEN_HEADER,token);
            log.info("createCoupon.req url={},paramMap={},token={}",domain+SupplierConstant.LH_CREATE_COUPON, JSON.toJSONString(param),token);
            ResponseEntity<JSONObject> result = restTemplateUtil.post(domain+SupplierConstant.LH_CREATE_COUPON, headers,param, JSONObject.class);
            log.info("createCoupon.resp url={},result={}",domain+SupplierConstant.LH_CREATE_COUPON, JSON.toJSONString(result));
            JSONObject jsonObject = result.getBody();
            restTemplateUtil.checkCodeException(jsonObject,SupplierTypeEnum.LI_HAN.getCode());
            String response = jsonObject.getStr("data");
            restTemplateUtil.checkDataException(response);
            List<LhCardSupplierResp> supplierCardCiphes = JSON.parseArray(response, LhCardSupplierResp.class);
            supplierCardCipherDTO = SupplierCardCipherDTO.conventSupplierCard(supplierCardCiphes.get(0));
            return supplierCardCipherDTO;
        }catch(Exception e){
            log.error("createCoupon resp error={}",e.getMessage());
            throw new CustomException(50000L,e.getMessage(),MethodUtil.getLineInfo());
        }
    }


    @Override
    public List<SupplierBaseDTO> getCouponBaseInfo(Object paraMap) {

        String domain = lhSupplierProperties.getDomain();
        List<SupplierBaseDTO> supplierSkuDTOList = new ArrayList<>();
        try {
            SupplierCouponReq supplierSkuReq = (SupplierCouponReq) paraMap;
            LhSupplierSkuReq lhSupplierSkuReq = new LhSupplierSkuReq();
            lhSupplierSkuReq.setCusSkuNoList(supplierSkuReq.getCusSkuNoList());
            Map<String, String> headers = new HashMap<>();
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String token = this.getToken(timestamp);
            headers.put(APP_KEY, lhSupplierProperties.getAppId());
            headers.put(TIMESTAMP, timestamp);
            headers.put(SupplierConstant.LH_TOKEN_HEADER, token);
            log.info("getCouponBaseInfo.req url={},paramMap={},headers={}", domain + SupplierConstant.LH_CARD_SKU_LIST, JSON.toJSONString(lhSupplierSkuReq), JSON.toJSONString(headers));
            ResponseEntity<JSONObject> result = restTemplateUtil.post(domain + SupplierConstant.LH_CARD_SKU_LIST, headers, lhSupplierSkuReq, JSONObject.class);
            log.info("getCouponBaseInfo.resp url={},result={}", domain + SupplierConstant.LH_CARD_SKU_LIST, JSON.toJSONString(result));
            JSONObject jsonObject = result.getBody();
            restTemplateUtil.checkCodeException(jsonObject, SupplierTypeEnum.LI_HAN.getCode());
            String response = jsonObject.getStr("data");
            restTemplateUtil.checkDataException(response);
            List<LhSupplierSkuResp> lhSupplierSkuResps = JSON.parseArray(response, LhSupplierSkuResp.class);
            if (CollectionUtils.isEmpty(lhSupplierSkuResps)) {
                return supplierSkuDTOList;
            }
            supplierSkuDTOList = lhSupplierSkuResps.stream().
                    map(lhSupplierSkuResp -> SupplierBaseDTO.convertBaseSupplierSku(lhSupplierSkuResp)).
                    collect(Collectors.toList());
            return supplierSkuDTOList;
        } catch (Exception e) {
            log.error("getCouponBaseInfo resp error={}", e.getMessage());
            throw new ServiceException(e.getMessage());
        }
    }


}
